<script setup lang='ts'>
import { ref } from 'vue';
import Nav from '@/components/index/Nav.vue'
import { reactive } from 'vue';
import { PromptInfo } from '@/models/prompt';
import { onMounted } from 'vue';
import { promptService } from '@/services/prompt.service';
import { appRef } from '@/models/app.ref';
import { appContext } from '@/models/app.context';
import router from '@/router';
import { Message } from '@arco-design/web-vue';
import { clipboardWriteText } from '@/utils/common.methods';
import { resolve } from 'path';
const columns = [
  {
    title: '角色名',
    dataIndex: 'role',
    ellipsis: true,
    width: 200
  },
  {
    title: '作者',
    dataIndex: 'author',
    ellipsis: true,
    width: 100
  },
  {
    title: 'prompt',
    dataIndex: 'value',
    ellipsis: true,
  },
  {
    title: '工作流',
    dataIndex: 'workflow',
    ellipsis: true,
  },
  {
    title: '标签',
    slotName: 'tags',
    width: 200,
  },
  {
    title: '操作',
    slotName: 'option',
    width: 150,
  },
];
const loading = ref(false);
const list = ref([]);
const tags = ref([]);
const currItem = ref({} as PromptInfo)
onMounted(() => {
  loading.value = true;
  init()
})
function init(): void {
  promptService.promptList().then(async () => {
    list.value = appRef.prompt.officialList;
    console.log(list.value);
    tags.value = await appRef.prompt.tags();
    visible.value = false;
    loading.value = false;
    isBatch.value = false;
    batch.value = '';
  })
}
const visible = ref(false);
async function onOk(isBatch?: false): Promise<void> {
  loading.value = true;
  try {
    const { role, value } = currItem.value;
    if (!role || !value) {
      new Error('不具备必填项')
      return;
    }
  } catch (error) {
    new Error('不具备必填项')
    return;
  }
  if (currItem.value.id) {
    await promptService.update(currItem.value)
  } else {
    await promptService.add([currItem.value])
  }
  if (!isBatch) init();
}
const isBatch = ref(false);
const batch = ref('');
async function onBatchOk(): Promise<void> {
  try {
    const list: PromptInfo[] = JSON.parse(batch.value);
    console.log(list);
    await Promise.all(list?.map(async val => {
      currItem.value = val;
      await onOk();
    }));
    Message.success("全部添加成功");
    init();
  } catch (error) {
    Message.error("批量操作失败，请检查格式")
  }
}
function onDelete(item: PromptInfo): void {
  loading.value = true;
  promptService.delete(item.id).then(() => init())
}


const search = ref('');
function onSearch(): void {
  list.value = appRef.prompt.officialList?.filter(val => val.role?.includes(search.value));
}

function onCopyAll(): void {
  clipboardWriteText(JSON.stringify(list.value))
}
</script>
<template>
  <div class="prompt">
    <a-page-header title="Prompt List" subtitle="admin 1.0" @back="router.replace('/')">
      <template #subtitle>
        <a-input-search :style="{ width: '320px' }" placeholder="请输入关键字搜索" v-model="search" @input="onSearch" />
      </template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="visible = true; currItem = JSON.parse(JSON.stringify({}))">新建</a-button>
          <a-button @click="onCopyAll">复制全部json</a-button>
          <a-button @click="isBatch = true">批量操作</a-button>
        </a-space>
      </template>
    </a-page-header>
    <main class="main">
      <a-table :columns="columns" :data="list" :loading="loading" :pagination="{ pageSize: 17 }">
        <template #tags="{ record }">
          <a-space>
            <a-tag color="arcoblue" size="small" v-for="tag in record?.tags">{{ tag }}</a-tag>
          </a-space>
        </template>
        <template #option="{ record }">
          <a-link @click="visible = true; currItem = JSON.parse(JSON.stringify(record))">编辑</a-link>
          <a-divider direction="vertical" />
          <a-popconfirm content="Are you sure you want to delete?" type="warning" @ok="onDelete(record)">
            <a-link status="danger">删除</a-link>
          </a-popconfirm>
        </template>
      </a-table>
    </main>
  </div>

  <a-modal :visible="visible" align-center @cancel="visible = false" width="50vw" :ok-loading="loading"
    :fullscreen="appContext.system.data.viewWidth < 1000" @ok="onOk()" :title="(currItem?.id ? '修改' : '创建') + ' Prompt'">
    <div class="group">
      <div class="cell">
        <div class="title red-dot">角色名</div>
        <a-input class="cell" v-model="currItem.role" placeholder="请输入角色名" />
      </div>
      <div class="cell">
        <div class="title red-dot">prompt 的详情</div>
        <a-textarea v-model="currItem.value" placeholder="请输入 prompt 的详情" :auto-size="{ minRows: 3, maxRows: 6 }" />
      </div>
      <div class="cell">
        <div class="title">角色的工作流描述</div>
        <a-textarea v-model="currItem.workflow" placeholder="建议完善该工作流，在后续使用提示更清晰" />
      </div>
      <div class="cell">
        <div class="title">作者</div>
        <a-input class="cell" v-model="currItem.author" placeholder="请输入作者" />
      </div>
      <div class="cell">
        <div class="title">标签</div>
        <a-select v-model="currItem.tags" placeholder="请选择或输入" multiple allow-create>
          <a-option v-for="tag in tags" :key="tag"> {{ tag }} </a-option>
        </a-select>
      </div>
      <div class="cell">
        <div class="title">连续对话</div>
        <a-switch v-model="currItem.continuous" :unchecked-value="0" :checked-value="1" />
      </div>
    </div>
  </a-modal>

  <a-modal :visible="isBatch" align-center @cancel="isBatch = false" width="50vw" :ok-loading="loading"
    :fullscreen="appContext.system.data.viewWidth < 1000" @ok="onBatchOk" title="批量管理Prompt">
    <div class="group">
      <div class="cell">
        <div class="title">可复制全部json改完之后直接</div>
        <div class="title">
          <a-space>
            <a-alert>批量创建（请勿填写id字段）</a-alert>
            <a-alert>批量修改（请勿修改id）</a-alert>
          </a-space>
        </div>
        <a-textarea v-model="batch" placeholder="请粘贴标准格式的json数组" :auto-size="{ minRows: 10, maxRows: 20 }" />
      </div>
    </div>
  </a-modal>
</template>
<style lang='scss' scoped>
.prompt {
  width: 100vw;
  min-height: 100vh;
  padding-top: 20px;
  background-image: radial-gradient(var(--color-neutral-2) 1px, var(--color-bg-1) 1px);
  background-size: 16px 16px;

  .main {
    padding: 0 20px;
  }
}

.group {

  .cell {
    margin-bottom: 10px;

    .title {
      margin-bottom: 6px;
    }
  }
}
</style>